package com.example.spring.demo.service.impl;

import com.example.spring.demo.common.error.CustomException;
import com.example.spring.demo.service.MinioService;
import io.minio.*;
import io.minio.errors.*;
import io.minio.http.Method;
import io.minio.messages.Item;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import java.util.stream.StreamSupport;

/**
 * @author qwert
 * @version 1.0.0
 * @create 2024/12/30 8:46
 **/
@Service
@RequiredArgsConstructor
public class MinioServiceImpl implements MinioService {

    private final MinioClient minioClient;

    @Value("${minio.bucket-name}")
    private String bucketName;

    public void ensureBucketExists() throws Exception {
        // 检查存储桶是否存在
        boolean found = minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());
        if (!found) {
            // 如果存储桶不存在，则创建
            minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build());
        }
    }

    // 上传文件
    public ObjectWriteResponse uploadFile(String objectName, MultipartFile file){
        try (InputStream inputStream = file.getInputStream()) {
            return minioClient.putObject(
                    PutObjectArgs.builder()
                            .bucket(bucketName)
                            .object(objectName)
                            .stream(inputStream, file.getSize(), -1)
                            .contentType(file.getContentType())
                            .build());
        } catch (Exception ex) {
            throw new CustomException("保存文件失败，请重试", ex.getMessage());
        }
    }

    // 下载文件
    public InputStream downloadFile(String objectName) throws Exception {
        return minioClient.getObject(
                GetObjectArgs.builder()
                        .bucket(bucketName)
                        .object(objectName)
                        .build());
    }

    // 列出存储桶中的所有对象
    public List<Item> listObjects() {
        try {
            Iterable<Result<Item>> results = minioClient.listObjects(
                    ListObjectsArgs.builder()
                            .bucket(bucketName)
                            .build()
            );

            // 使用 Stream 转换 Iterable 到 List<Item>
            return StreamSupport.stream(results.spliterator(), false)
                    .map(this::extractItem) // 提取 Item
                    .collect(Collectors.toList());

        } catch (Exception e) {
            // 处理可能发生的异常
            System.err.println("Error listing objects in bucket " + bucketName + ": " + e.getMessage());
            return List.of(); // 返回一个空列表以防止空指针异常
        }
    }

    @Override
    public String getObjectUrl(String objectName) {
        try {
            return minioClient.getPresignedObjectUrl(
                    GetPresignedObjectUrlArgs.builder()
                            .bucket(bucketName)
                            .object(objectName)
                            .method(Method.GET)
                            .build());
        } catch (Exception e) {
            throw new CustomException("获取图片URL失败：" + e.getMessage());
        }
    }

    @Override
    public String getObjectUrl(String objectName, int time) {
        try {
            return minioClient.getPresignedObjectUrl(
                    GetPresignedObjectUrlArgs.builder()
                            .bucket(bucketName)
                            .object(objectName)
                            .method(Method.GET)
                            .expiry(time, TimeUnit.MINUTES)
                            .build());
        } catch (Exception e) {
            throw new CustomException("获取图片URL失败：" + e.getMessage());
        }
    }


    private Item extractItem(Result<Item> result) {
        try {
            return result.get();
        } catch (Exception e) {
            System.err.println("Error extracting item: " + e.getMessage());
            return null;
        }
    }

}
